package control
{
   import flash.display.MovieClip;
   import flash.events.Event;
   import flash.text.TextField;
   import flash.text.TextFieldAutoSize;
   import flash.text.TextFieldType;
   import flash.text.TextFormat;

   public class SimpleColorPicker extends MovieClip
   {
      private var textField: TextField = new TextField
      private var _color: uint = 0
      private var _caption: TextField
      
      private var colorBoxX: Number = 0
      private var colorBoxY: Number = 0

      public function SimpleColorPicker()
      {
         super();
         addEventListener(Event.ADDED_TO_STAGE, function ():void{init()})
      }
      
      private function init (): void {
         textField.type = TextFieldType.INPUT
         textField.x = 25
         textField.y = 0
         textField.width = 60
         textField.height = 18
         textField.border = true
         textField.borderColor = 0xFFFFFF
         textField.defaultTextFormat = new TextFormat("Arial", 12, 0xFFFFFF)
         textField.addEventListener(Event.CHANGE, onChangeText)
         addChild(textField)
         redraw()
      }

      private function redraw (): void {
         graphics.clear()
         graphics.lineStyle(1, 0xFFFFFF, 1, true)
         graphics.beginFill(_color)
         graphics.drawRect(colorBoxX, colorBoxY, 18, 18)
         graphics.endFill()
         graphics.lineStyle()
         textField.x = colorBoxX + 25
      }
      
      private function onChangeText (event:Event): void {
         _color = uint("0x" + textField.text)
         dispatchEvent(event)
         redraw()
      }
      
      public function get color (): uint {
         return _color
      }

      public function set color (value:uint): void {
         _color = value
         redraw()
      }
      
      public function get caption (): String {
         if (_caption) return ""
         return _caption.text
      }
      
      public function set caption (value:String): void {
         if (_caption == null) {
            _caption = new TextField
            _caption.type = TextFieldType.DYNAMIC
            _caption.x = 0
            _caption.y = 0
            _caption.height = 18
            _caption.autoSize = TextFieldAutoSize.LEFT
            _caption.defaultTextFormat = new TextFormat("Arial", 12, 0x999999)
            addChild(_caption)
         }

         if (value == "") {
            removeChild(_caption)
            _caption = null
            colorBoxX = 0
         } else {
            _caption.text = value
            colorBoxX = _caption.width + 10
            colorBoxY = 0
         }
         redraw()
      }  
      
   }
}